//
// Created by LiuYou on 2021/5/7.
//

#include <cstdio>
#include <cstring>
#include <cerrno>
#include <cstdlib>


int computeFileSize(char* const* argv);

/**
 * @brief MyCopy
 */
int main(int argc, char** argv) {
    // todo 注意: 当使用了命令行参数一定一定要main函数的开始对argc进行判断！！！！
    if (argc < 3) {
        std::fprintf(stderr, "Usage: %s <srcFile> <destFile>\n", basename(argv[0]));
        std::exit(1);
    }

    FILE* sourceFilePtr = std::fopen(argv[1], "r");
    if (sourceFilePtr == nullptr) {
        std::fprintf(stderr, "fopen(): %s\n", std::strerror(errno));
        std::exit(1);
    }
    FILE* destinationFilePtr = std::fopen(argv[2], "w");
    if (destinationFilePtr == nullptr) {
        std::fclose(sourceFilePtr);
        std::fprintf(stderr, "fopen(): %s\n", std::strerror(errno));
        std::exit(1);
    }
    const int BUF_SIZE = 1024;
    char buf[BUF_SIZE]{};
    for (;;) {
        // 最多能读BUF_SIZE-1个有效字符, 因为第1024个字符一定是'\0'。
        if (std::fgets(buf, BUF_SIZE, sourceFilePtr) != nullptr) {
            std::fputs(buf, destinationFilePtr);
        } else {
            break;
        }
    }

    std::fprintf(stdout, "源文件的大小为: %d 个字节。\n", computeFileSize(argv));
    std::fclose(destinationFilePtr);
    std::fclose(sourceFilePtr);

    return 0;
}

int computeFileSize(char* const* argv) {
    FILE* pFile = fopen(argv[1], "r");
    if (pFile == nullptr) {
        fprintf(stderr, "fopen(): %s", strerror(errno));
        exit(1);
    }
    int count = 0;
    for (;;) {
        if (fgetc(pFile) != EOF) {
            ++count;
        } else {
            break;
        }
    }
    fclose(pFile);
    return count;
}
